<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抽签系统</title>
<style>
    #scroll-container {
        height: 80vh;
        overflow: hidden;
        position: relative;
        margin: 20px auto;
        width: 80%;
        border: 2px solid #4CAF50;
        border-radius: 8px;
    }
    .name-item {
        font-size: 2.5rem;
        padding: 1rem;
        text-align: center;
        color: #2196F3;
        font-weight: bold;
        transition: all 0.3s;
    }
    @keyframes popIn {
        0% { transform: scale(0) translate(-50%, -50%); }
        80% { transform: scale(1.1) translate(-50%, -50%); }
        100% { transform: scale(1) translate(-50%, -50%); }
    }
</style>
</head>
<body>
    <h1>欢迎使用抽签系统</h1>
    <div id="lottery-result"></div>
    
        function drawLottery() {
            // 这里可以添加抽签逻辑
            document.getElementById('lottery-result').innerHTML = '抽签结果将在后端处理';
        }
    </script>
    <div style="text-align: center; margin: 20px;">
        <select id="class-select" style="margin-right: 15px;"></select>
        <button onclick="startRotation()" style="margin-right: 15px;">开始</button>
        <button onclick="stopRotation()">停止</button>
    </div>
    <div id="result-box" style="display: none; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
        padding: 20px 40px; background: #f0f8ff; border-radius: 15px; box-shadow: 0 0 10px rgba(0,0,0,0.2);
        font-size: 2em; font-weight: bold;">    <div id="scroll-container" style="height: 200px; overflow: hidden; border: 2px solid #4CAF50; border-radius: 8px; margin: 20px 0;"></div>
</div>
<div id="loading-indicator" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
    background: rgba(0,0,0,0.8); color: white; padding: 15px 30px; border-radius: 5px;">
    加载中，请稍候...
</div>
</body>
</html>
<script>
// 错误处理函数
function showError(message) {
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert) {
        errorAlert.textContent = message;
        errorAlert.classList.remove('d-none');
        setTimeout(() => errorAlert.classList.add('d-none'), 5000);
    }
}

let students = [];
let isLoading = false;
let animationInterval;
let isScrolling = false; // 新增滚动状态标识
let rotationEnabled = true; // 新增旋转控制标识
const scrollSpeed = 50;

window.addEventListener('DOMContentLoaded', async () => {
    try {
        const scrollContainer = document.getElementById('scroll-container');
        if (!scrollContainer) throw new Error('未找到滚动容器元素');

        // 统一事件绑定在此处
        const select = document.getElementById('class-select');
        select.innerHTML = ''; // 清空原有选项

        const { classes } = await fetch('/get_choosed_classes').then(r => r.json());
        classes.forEach(c => {
            const option = document.createElement('option');
            option.value = c;
            option.textContent = c;
            select.appendChild(option);
        });

        // 保留唯一的事件处理程序
        select.addEventListener('change', async () => {
            // 添加容器存在性检查
            if (!scrollContainer) {
                showError('滚动容器未初始化');
                return;
            }
            try {
                isLoading = true;
                document.getElementById('loading-indicator').style.display = 'block';
                
                const response = await fetch(`/get_students_by_class?class_id=${encodeURIComponent(select.value)}`);
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `HTTP错误! 状态码: ${response.status}`);
                }
                
                students = await response.json();
                if (!Array.isArray(students) || students.length === 0) {
                    throw new Error('该班级没有学生数据');
                }
                
                initScrollArea();
            } catch (error) {
                console.error('加载学生失败:', error);
                scrollContainer.innerHTML = `<div class="error">加载失败: ${error.message}</div>`;
                students = []; // 清空学生数据
            } finally {
                isLoading = false;
                document.getElementById('loading-indicator').style.display = 'none';
            }
        });

    } catch (error) {
        console.error('初始化失败:', error);
        document.getElementById('lottery-result').innerHTML = `初始化失败：${error.message}`;
    }
});

// 移除重复的fetch('/get_choosed_classes')代码块
// 初始化滚动区域
function initScrollArea() {
    const container = document.getElementById('scroll-container');
    if (!container) {
        showError('滚动容器未找到');
        return;
    }
    container.innerHTML = students.map(name => 
        `<div class="name-item">${name}</div>`
    ).join('');
}

// 获取学生数据
// 移除重复的班级选择器事件监听
// 保留DOMContentLoaded中的事件绑定

async function loadStudents(classId) {
    try {
        const response = await fetch(`/get_students_by_class?class_id=${encodeURIComponent(classId)}`);
        if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
        const data = await response.json();
        if (!Array.isArray(data)) throw new Error('无效的学生数据格式');
        students = data;
        initScrollArea();
    } catch (error) {
        console.error('加载学生失败:', error);
        document.getElementById('scroll-container').innerHTML = 
            `<div class="error">加载失败: ${error.message}</div>`;
        students = [];
        throw error;
    }
}

// 窗口自适应
window.addEventListener('resize', () => {
    
});

// 初始化


// 填充班级选项
fetch('/get_choosed_classes')
    .then(r => r.json())
    .then(data => {
        const select = document.getElementById('class-select');
        data.classes.forEach(c => {
            const option = document.createElement('option');
            option.value = c;
            option.textContent = c;
            select.appendChild(option);
        });
            select.removeEventListener('change', null);
    select.addEventListener('change', async () => {
        try {
            isLoading = true;
            document.getElementById('loading-indicator').style.display = 'block';
            
            const response = await fetch(`/get_students_by_class?class_id=${encodeURIComponent(select.value)}`);
            
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(`${errorData.error || '请求失败'} (状态码: ${response.status})`);
            }
            
            students = await response.json();
            if (!Array.isArray(students) || students.length === 0) {
                throw new Error('该班级没有学生数据');
            }
            
            initScrollArea();
        } catch (error) {
            console.error('加载学生失败:', error);
            document.getElementById('scroll-container').innerHTML = 
                `<div class="error">加载失败: ${error.message}</div>`;
            students = [];
        } finally {
            isLoading = false;
            document.getElementById('loading-indicator').style.display = 'none';
        }
    });
        // 移除重复事件绑定
    });

function startRotation() {
    const classSelect = document.getElementById('class-select');
    if (!classSelect.value) {
        alert('请先选择班级');
        return;
    }
    if (isLoading) {
        alert('数据正在加载中，请稍候...');
        return;
    }
    if (students.length === 0) {
        alert('当前班级没有学生数据，请先选择班级并等待数据加载完成');
        return;
    }
    
    isScrolling = true;
    startScrollAnimation();
    document.getElementById('result-box').style.display = 'none';
}

function stopRotation() {
    rotationEnabled = false;
    const resultBox = document.getElementById('result-box');
    resultBox.textContent = students[Math.floor(Math.random() * students.length)];
    resultBox.style.display = 'block';
}
</script>
.error {
    color: #dc3545;
    padding: 15px;
    border: 1px solid #dc3545;
    border-radius: 4px;
    margin: 10px 0;
}

div.alert {
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    min-width: 300px;
}

// 在页面添加错误显示区域
<div id="errorAlert" class="alert alert-danger d-none mt-3" role="alert"></div>




function startScrollAnimation() {
    const container = document.getElementById('scroll-container');
    if (!container) {
        showError('滚动容器未找到');
        return;
    }
    
    let position = 0;
    container.style.transition = 'none';
    container.style.transform = `translateY(${position}px)`;

    animationInterval = setInterval(() => {
        if (!rotationEnabled) {
            clearInterval(animationInterval);
            return;
        }
        position -= scrollSpeed;
        container.style.transition = 'transform 0.1s linear';
        container.style.transform = `translateY(${position}px)`;
        
        if (Math.abs(position) >= container.scrollHeight - container.clientHeight) {
            position = 0;
            container.style.transition = 'none';
            container.style.transform = `translateY(${position}px)`;
        }
    }, 100);
}

// 移除重复的班级选择器事件绑定
</script>
.error {
    color: #dc3545;
    padding: 15px;
    border: 1px solid #dc3545;
    border-radius: 4px;
    margin: 10px 0;
}

div.alert {
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    min-width: 300px;
}